<template>
    <div class="materials">

        <!-- 贴顶导航 -->
        <UserFixedHead>Embroidery File</UserFixedHead>

        <!-- 贴顶表单 -->
        <UserFixedForm padding="0 180px">
            <UserSearchName v-model="keywords" size="medium" shape="solid" placeholder="File name"
                            @change="getSearching($event)" />
            <UserSearchButton size="medium" shape="text" name="Upload" icon="user-files-upload" @click="fileUpload()" />
        </UserFixedForm>

        <!-- 初始化 -->
        <UxIniting v-if="!inited" />

        <!-- 全局为空 -->
        <div class="nodata" v-else-if="empty && !loading">
            <h2>
                <strong>Embroidery File</strong>

                <span>You can use
                    <ProductEmbDstTip /> format embroidery files to maintain the utmost fidelity to your original design
                    in your embroidered garments.
                    (<a href="/document/embroidery-dst" target="_blank">What Is a DST File and How to Get One</a>)
                </span>
            </h2>
            <ul>
                <li>
                    <figure>
                        <img src="@/assets/images/files/emb-empty.png" alt="" />
                    </figure>
                    <h3>Turn your ideas into a product</h3>
                    <UserSearchButton shape="solid" name="Upload" icon="user-files-upload" @click="fileUpload()" />
                </li>
            </ul>

            <p>
                <i>c</i>
                Make sure you have read our <a href="/document/privacy-policy">Privacy policy</a> and <a
                   href="/document/terms-service">Terms of service</a>.
            </p>
        </div>

        <div class="materials-body" v-else>

            <h2>Embroidery File</h2>

            <!-- 搜索框 -->
            <div class="form">
                <UserSearchName v-model="keywords" shape="plain" placeholder="File name"
                                @change="getSearching($event)" />
                <span style="flex:1;"></span>
                <UserSearchButton shape="solid" name="Upload" icon="user-files-upload" @click="fileUpload()" />
            </div>

            <UxLoading2 v-if="loading" :loading="loading" />

            <!-- 搜索 -->
            <div class="searching" v-else-if="form.name">

                <MaterialsEmbroiderySelected :list="list" :selected.sync="selected" @reload="reload()">
                    <div class="search-match">
                        <strong v-text="form.total"></strong>
                        <em v-if="form.total > 1"> matches found</em>
                        <em v-else> match found</em>
                    </div>
                </MaterialsEmbroiderySelected>

                <UxSearchEmpty v-if="list.length == 0" />
                <MaterialsEmbroideryList v-else :list="list" :selected.sync="selected" :editable="true"
                                         @edit="doEdit($event)" />
            </div>

            <!-- 外层管理 -->
            <div class="manage" v-else>
                <!-- 最近使用 -->
                <template v-if="recently.length > 0">
                    <h3><strong>Recently used</strong></h3>
                    <MaterialsEmbroideryList :list="recently" :selected.sync="selected" :editable="true"
                                             @edit="doEdit($event)" class="manage-recently" />
                </template>

                <!-- 图片列表 -->
                <template v-if="imageList.length > 0">
                    <MaterialsEmbroiderySelected :list="imageList" :selected.sync="selected" @reload="reload()">
                        <strong>My files</strong>
                    </MaterialsEmbroiderySelected>
                    <MaterialsEmbroideryList :list="imageList" :selected.sync="selected" :editable="true"
                                             @edit="doEdit($event)" />
                </template>
            </div>

            <div class="nomore" v-show="list.length > 0 && form.status != 'nomore'">
                <span v-if="form.status == 'loading'">-- Scroll to bottom load data --</span>
                <span v-if="form.status == 'waiting'">-- Loading --</span>
                <!-- <span v-if="activeInfo.status == 'nomore'">-- All data loaded --</span> -->
            </div>
        </div>

        <!-- 上传的弹窗 -->
        <MaterialsEmbroideryUpload v-model="upload" :uploaded.sync="uploaded" @reload="uploadedReload()" />

        <!-- 编辑弹窗 -->
        <DesignerEmbDstEditDialog scenes="files" />

    </div>
</template>
<script>
import { colors } from "@/utils/EmbroideryPattern.js";
import { getStitchesByBase64 } from "@/utils/EmbroideryDst.js";
import { writeCanvas } from "@/utils/EmbroideryCanvas.js";
import { mapGetters } from "vuex";
import Md5 from "js-md5";


export default {
    name: "UserMaterials",
    layout: "layout-user",
    data () {
        return {
            inited: false,
            loading: false,
            keywords: "",

            recently: [], // 最近使用
            selected: [], // 选中的图片id
            uploaded: [], // 上传中的

            form: { name: '', page: 1, size: 15, status: '', total: 0, },
            list: [],

            folder: null, // 文件夹编辑器
            upload: null,
            preview: null
        };
    },
    computed: {
        ...mapGetters("user", {
            userInfo: "getUserInfo",
        }),
        imageList () {
            return this.uploaded.concat(this.list)
        },
        empty () {
            if (this.form.name) {
                // 搜索或是路径中
                return false;
            } else {
                return this.uploaded.length == 0 && this.list.length == 0 && this.recently.length == 0
            }
        },
    },

    methods: {
        // 最近使用
        async getRecently () {
            let response = await this.$http("Material.getEmbUploadUsed/5", {});
            this.recently = response.data || [];
        },

        // 获取用户图片
        async getResourceList () {

            let request = {
                search_name: this.form.name,
                page_num: this.form.page,
                page_size: this.form.size,
            };

            let response = await this.$http("Material.getEmbList", request);
            let list = (response.data || []).map(item => {
                item.type = '';
                item.file = null;
                item.image = null;
                item.percent = 0;
                item.error = '';
                return item;
            })


            // 清空数据
            if (request.page_num == 1) {
                this.list.splice(0, this.list.length);
                this.list = list;
                // 把只保存上传中的（上传失败，上传成功的都会清掉）
                this.uploaded = this.uploaded.filter(i => i.type == 'uploading')

            } else {
                this.list.push(...list)
            }

            this.form.total = response.total || 0;
            this.form.status = list.length < this.form.size ? "nomore" : "waiting";
        },

        // 搜索功能
        getSearching () {
            const keywords = (this.keywords || "").trim()
            this.form.name = keywords;
            this.form.page = 1;
            this.form.status = "";
            this.loading = true;
            this.selected = [];
            this.list = [];
            this.getResourceList().then(res => this.loading = false);
        },

        // 上传完成后更新
        uploadedReload () {
        },

        // 生成预览图
        getThumb (stitches, line_color) {

            const codes = line_color.split(',').filter(i => i)
            const colorFormat = codes.map(i => colors.find(c => c.code == i)).filter(i => i)
            const canvas = writeCanvas(getStitchesByBase64(stitches), colorFormat)
            const email = (this.userInfo || {}).email;
            const folder = email ? Md5(email) : 'noemail';
            const path = ('data/pod/file/' + folder).replace(/\/+$/, '') + '/';

            const time = new Date().getTime();
            const random = Math.random().toFixed(10).substring(2);

            return new Promise((resolve, reject) => {
                canvas.toBlob(blob => {
                    const request = {
                        file: blob,
                        name: time + "-" + random + ".png",
                        path: path,
                    };
                    this.$uploadToOSS(request, response => {
                        if (response.code === 0 && response.data) {
                            resolve(response.data || '');
                        } else {
                            reject(response.msg || "Please check your network connection and try again.");
                        }
                    })

                }, "image/png", 1)
            })
        },

        // 编辑
        doEdit (item) {

            const option = {
                stitches: item.stitches,
                stitches_count: item.stitches_count,
                line_color: item.line_color,
                dst_name: item.file_name,
                dst_width: item.width,
                dst_height: item.height,
                callback: (dst) => {
                    this.loading = true;
                    this.getThumb(dst.stitches, dst.line_color).then(url => {
                        const request = {
                            img_url: url,
                            line_color: dst.line_color,
                            file_name: dst.dst_name,
                            color_unedited: 1,
                        }
                        const keys = Object.keys(request)
                        this.list.map(i => i.id == item.id && keys.map(key => this.$set(i, key, request[key])))
                        this.recently.map(i => i.id == item.id && keys.map(key => this.$set(i, key, request[key])))
                        this.uploaded.map(i => i.id == item.id && keys.map(key => this.$set(i, key, request[key])))

                        return this.$http("Material.setEmbDetail/" + item.id, request);
                    }).then(res => {
                        if (res.code === 0) {
                            this.$uxMessage.success('Embroidery file updated successfully!');
                            this.loading = false;
                        } else {
                            return Promise.reject(res.msg)
                        }
                    }).catch(err => {
                        // this.$uxMessage.error(err);
                        console.log(err);
                        this.loading = false;
                    })
                }
            }
            this.$emit("global:DESIGN_OPEN_EMB_DST_EDIT_DIALOG", option);

        },

        // 重新加载
        reload () {
            this.form.page = 1;
            this.form.status = '';
            this.selected = []
            this.loading = true;
            Promise.all([this.getRecently(), this.getResourceList()]).then(() => {
                this.loading = false
                this.$emit('global:onscroll')
            })
        },

        // 滚动加载事件
        onScroll (event) {
            if (this.form.status == "waiting") {
                let offset = 10;
                let scrollHeight = document.body.clientHeight;
                let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
                let clientHeight = document.documentElement.clientHeight;

                if (scrollHeight - clientHeight - scrollTop < offset) {
                    this.form.status = "loading";
                    this.form.page += 1;
                    this.getResourceList();
                }
            }
        },

        // 文件上传
        fileUpload () {
            this.upload = true;
        },

        // 添加或编辑文件夹名称
        editFolder (item) {
            this.folder = item || {};
        },


    },
    created () {
        if (process.client) {
            Promise.all([this.getRecently(), this.getResourceList()]).then(() => this.inited = true);
            window.addEventListener("scroll", this.onScroll);
        }
    },
    beforeDestroy () {
        window.removeEventListener("scroll", this.onScroll);
    },
};
</script>
<style lang="scss" scoped>
.materials {
    position: relative;
    display: flex;
    flex-direction: column;

    .user-fixed-head {
        display: flex;
        align-items: center;

        &::v-deep .user-fixed-head-title span {
            max-width: 140px;
            white-space: nowrap;
            text-overflow: ellipsis;
            overflow: hidden;
        }

        a {
            cursor: pointer;
        }

        button {
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 8px;
            font-weight: normal;
            pointer-events: all;
            border-radius: 4px;

            &:hover {
                background-color: #f3f3f3;
                color: #000;
            }

            i {
                font-size: 12px;
            }
        }
    }

    .user-fixed-form {
        .user-search-name {
            margin-right: 16px;
        }

        .user-search-button {
            width: auto;
            margin-left: 8px;
        }
    }
}

.initing {
    flex: 1;
}

.nodata {
    flex: 1;

    h2 {
        display: flex;
        flex-direction: column;

        strong {
            height: 40px;
            font-size: 36px;
            font-family: Roboto-Medium, Roboto;
            font-weight: 500;
            color: #000000;
            line-height: 40px;
        }

        span {
            margin-top: 24px;
            font-family: Roboto-Regular, Roboto;
            font-weight: 400;
            font-size: 16px;
            color: #555555;
            line-height: 22px;

            a {
                font-weight: 400;
                color: #087196;
                cursor: pointer;
                text-decoration: underline;
                margin: 0 4px;

                &:hover {
                    color: #075e7d;
                    text-decoration: none;
                }
            }
        }
    }

    p {
        margin-top: 40px;
        font-size: 14px;
        font-family: Roboto-Regular, Roboto;
        font-weight: 400;
        color: #000000;
        line-height: 20px;
        display: flex;
        align-items: center;

        i {
            width: 14px;
            height: 14px;
            line-height: 12px;
            font-size: 12px;
            text-align: center;
            border-radius: 4px;
            background: #000;
            color: #fff;
            margin-right: 4px;
        }

        a {
            font-weight: 400;
            color: #087196;
            cursor: pointer;
            text-decoration: underline;
            margin: 0 4px;

            &:hover {
                color: #075e7d;
                text-decoration: none;
            }
        }
    }

    ul {
        display: flex;
        background: #ffffff;
        border-radius: 8px;
        border: 1px solid #e6e6e6;
        padding: 28px;
        margin-top: 24px;
    }

    li {
        display: flex;
        align-items: center;
        flex: 1;
        flex-direction: column;

        figure {
            width: 100%;
            position: relative;
            background: #f8f8f8;
            border-radius: 6px;

            &::before {
                content: "";
                display: block;
                padding-bottom: 31.25%;
            }

            img {
                position: absolute;
                height: 100%;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
        }

        h3 {
            margin-top: 20px;
            font-size: 16px;
            font-family: Roboto-Regular, Roboto;
            font-weight: 400;
            color: #212121;
            line-height: 16px;
        }

        .user-search-button {
            margin-top: 20px;
            width: 140px;
        }

        &+li {
            margin-left: 28px;
        }
    }
}

.materials-body {
    flex: 1;
    display: flex;
    flex-direction: column;
    position: relative;

    &>h2 {
        display: flex;
        align-items: center;
        font-size: 36px;
        font-family: Roboto-Medium, Roboto;
        font-weight: 500;
        color: #000000;
        line-height: 40px;
        white-space: nowrap;

        i {
            margin: 0 8px;
            font-size: 16px;
            color: #555;
            font-weight: normal;
        }

        a {
            cursor: default;
            color: #555;

            &:hover {
                color: #000;
            }
        }

        a:first-child {
            cursor: pointer;
        }

        a:last-child {
            color: #000;
            overflow: hidden;
            text-overflow: ellipsis;
        }
    }

    &>.loading {
        position: fixed;
        left: 228px;
        top: 0;
        bottom: 0;
        right: 0;
    }

    &>.nomore {
        height: 30px;
        line-height: 30px;
        text-align: center;
    }
}

.form {
    display: flex;
    margin-top: 40px;

    .user-search-button {
        width: 140px;
        margin-left: 8px;
    }
}

.manage {
    flex: 1;

    &>h3,
    &>.files-select {
        display: flex;
        margin-top: 40px;
        position: relative;
        height: 18px;

        strong {
            height: 18px;
            font-size: 18px;
            font-family: Roboto-Medium, Roboto;
            font-weight: 500;
            color: #000000;
            line-height: 18px;
        }
    }

    .manage-recently::v-deep {
        figure>i {
            display: none !important;
        }
    }

    .image-list {
        margin-top: 18px;
    }

    .folder-list {
        margin-top: 8px;
    }
}

.searching {

    &>h3,
    &>.files-select {
        display: flex;
        margin-top: 48px;
        position: relative;

        strong {
            font-size: 22px;
            font-family: Roboto-Medium, Roboto;
            font-weight: 500;
            color: #000000;
            line-height: 22px;
            margin-right: 4px;
        }

        em {
            font-size: 22px;
            font-family: Roboto-Medium, Roboto;
            font-weight: 500;
            color: #000000;
            line-height: 22px;
            margin-right: 4px;
        }
    }

    .image-list {
        margin-top: 18px;
    }

    .search-empty {
        margin-top: 18px;
        height: 600px;
        background: #ffffff;
        border-radius: 8px;
        border: 1px solid #e6e6e6;
    }
}

.materials-popover {
    font-size: 14px;
    font-weight: normal;
    color: #000;
    line-height: 20px;
}

.filebox {
    position: absolute;
    left: 0;
    top: 0;
    width: 0;
    height: 0;
    overflow: hidden;
    opacity: 0;
    outline: none;
    user-select: none;
    pointer-events: none;
}
</style>
